package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.utils.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@RestController("adminDishController")
@RequestMapping("/admin/dish")
@Api(tags = "菜品相关接口")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result dishList(DishPageQueryDTO dishPageQueryDTO){
        return dishService.dishList(dishPageQueryDTO);
    }

    @PostMapping
    @ApiOperation("新增菜品")
    public Result saveDish(@RequestBody DishDTO dishDTO){
        Result result = dishService.saveDish(dishDTO);
        //TODO 清除缓存数据
        String key = "dish_"+dishDTO.getCategoryId();
        cleanCache(key);
        return result;
    }

    @DeleteMapping
    @ApiOperation("批量删除菜品")
    public Result deleteDishes(String ids){
        Result result = dishService.deleteDishes(ids);
        //TODO 清除缓存数据
        cleanCache("dish_*");
        return result;
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询菜品")
    public Result getDishById(@PathVariable String id){
        return dishService.getDishById(id);
    }

    @PutMapping
    @ApiOperation("修改菜品")
    public Result updateDish(@RequestBody DishDTO dishDTO){
        Result result = dishService.updateDish(dishDTO);
        //TODO 清除缓存数据
        cleanCache("dish_*");
        return result;
    }

    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result getDishesByType(String categoryId){
        return dishService.getDishesByType(categoryId);
    }

    /**
     *全部清理 为啥不是精确清除？
     * 当某个菜品修改为停售状态的时候，该菜品所属的套餐信息应该是要清除缓存的，但是如果
     * 在修改菜品状态的时候使用的是精确清除缓存，那么所属套餐的信息缓存就没被清除。。
     */
    @PostMapping("/status/{status}")
    @ApiOperation("菜品起售、停售")
    public Result updateDishStatus(@PathVariable String status, String id){
        Result result = dishService.updateDishStatus(status, id);
        //TODO 清除缓存数据
        cleanCache("dish_*");
        return result;
    }

    /**
     * 清理缓存方法
     * 删除redis中key为dish_开头的所有键值对
     * @param pattern
     */
    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

}
